//
//  UIViewController+YTAdd.m
//  tesDemo02
//
//  Created by 拓客营 on 2022/3/22.
//

#import "UIViewController+YTAdd.h"
#import <objc/runtime.h>
#import "AppDelegate.h"
#import <MobileCoreServices/MobileCoreServices.h>

@interface YTUIViewControllerImagePickerDelegator : NSObject<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, copy) void (^callback)(NSError *error, UIImage *image);

@end


@implementation YTUIViewControllerImagePickerDelegator

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = info[UIImagePickerControllerEditedImage];
        NSError *error = nil;
        if (!image) {
            error = [NSError errorWithCode:2001 message:@"未选择图片"];
        }
        if (self.callback) {
            self.callback(error, image);
        }
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

@end


@implementation UIViewController (YTAdd)

// 为类别添加属性
static const void *classNamePickerControllerKey = &classNamePickerControllerKey;

-(void)setPickerController:(TZImagePickerController *)pickerController {
    objc_setAssociatedObject(self, classNamePickerControllerKey, pickerController, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(TZImagePickerController *)pickerController {
    return  objc_getAssociatedObject(self, classNamePickerControllerKey);
}

- (void)dismissController{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)popController{
    if (!self.navigationController) {
        return;
    }
    if ([self.navigationController.childViewControllers indexOfObject:self] == 0) {
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setTitle:(nullable NSString *)title titleColor:(UIColor *)color {
    
    if (!title) {
        self.navigationItem.titleView = nil;
        return;
    }
    
    NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:title];
    attributedTitle.font = [UIFont systemFontOfSize:18.f];
    attributedTitle.color = color;
    
    
    CGSize textSize = [attributedTitle size];
    
    UILabel *titleLabel = (UILabel *)self.navigationItem.titleView;
    
    if (!titleLabel) {
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, textSize.width, self.navigationController.navigationBar.height)];
        titleLabel.clipsToBounds = YES;
    }
    
    titleLabel.attributedText = attributedTitle;
    [titleLabel sizeToFit];
    self.navigationItem.titleView = titleLabel;
}


- (void)yt_presentViewController:(UIViewController *)controller animated:(BOOL)flag completion:(nullable void (^)(void))completion {
    
    if (@available(iOS 13.0, *)) {
        
       controller.modalPresentationStyle = UIModalPresentationFullScreen;
    }

    [self presentViewController:controller animated:flag completion:completion];
}

- (void)presentImagePickerControllerWithCallback:(imagePickerCallback)callback{
    
    if (TARGET_IPHONE_SIMULATOR) {
        NSLog(@"这个是模拟器");
        return;
    }
    
    BOOL availableType = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!availableType) {
        NSLog(@"不可用");
        return;
    }
    
    //后置摄像头
    BOOL availableCameraRear = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    
    BOOL availableCameraFront = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!availableCameraRear && !availableCameraFront) {//前后摄像头都不能用  o(╯□╰)o
        [MBProgressHUD showMessage:@"摄像头暂时无法使用" toView:self.view];
        return;
    }
    
    YTUIViewControllerImagePickerDelegator *delegator = [YTUIViewControllerImagePickerDelegator new];
    
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    
    controller.sourceType = UIImagePickerControllerSourceTypeCamera;
    controller.cameraDevice = availableCameraRear ? UIImagePickerControllerCameraDeviceRear : UIImagePickerControllerCameraDeviceFront;
    controller.allowsEditing = YES;
    controller.delegate = delegator;
    [self yt_presentViewController:controller animated:YES completion:NULL];
    
    delegator.callback = ^(NSError *error, UIImage *image) {
        if (callback) {
            callback(error, image);
        }
    };
    
}

- (void)presentRecordImagePickerControllerWithDelegator:(id<UIImagePickerControllerDelegate,UINavigationControllerDelegate>)delegate {
    
    if (TARGET_IPHONE_SIMULATOR) {
        NSLog(@"这个是模拟器");
        return;
    }
    
    BOOL availableType = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!availableType) {
        NSLog(@"不可用");
        [UIAlertController alertWithController:self title:@"摄像头无法使用，请检查" message:nil actionTitles:@[@"确定"] actionOne:nil actionTwo:nil];
        return;
    }
    
    //后置摄像头
    BOOL availableCameraRear = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    
    BOOL availableCameraFront = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!availableCameraRear && !availableCameraFront) {//前后摄像头都不能用  o(╯□╰)o
        [MBProgressHUD showMessage:@"摄像头暂时无法使用" toView:self.view];
        return;
    }
    
    UIImagePickerController *pickerContr = [[UIImagePickerController alloc]init];
    //设置资源类型
    [pickerContr setSourceType:UIImagePickerControllerSourceTypeCamera];
    if ([self isAvalableMediaType:kUTTypeMovie sourcType:UIImagePickerControllerSourceTypeCamera]) {
        //配置媒体类型
         [pickerContr setMediaTypes:@[(__bridge NSString *)kUTTypeMovie]];
        //配置视频质量
        [pickerContr setVideoQuality:UIImagePickerControllerQualityTypeHigh];
        //设置最大录制时间
        [pickerContr setVideoMaximumDuration:10];
        //设置代理
        pickerContr.delegate = delegate;
        [self presentViewController:pickerContr animated:YES completion:nil];
    }else{
        
        [UIAlertController alertWithController:self title:@"摄像头无法使用，请检查" message:nil actionTitles:@[@"确定"] actionOne:nil actionTwo:nil];
    }
    
}

-(BOOL)isAvalableMediaType:(CFStringRef)mediaType sourcType:(UIImagePickerControllerSourceType)soureType{
    NSArray *array =  [UIImagePickerController availableMediaTypesForSourceType:soureType];
    NSLog(@"%@",array);
    return [array containsObject:(__bridge NSString *)mediaType];
}


- (void)presentImagePickerControllerWithDelegator:(id<UIImagePickerControllerDelegate,UINavigationControllerDelegate>)delegate{
    if (TARGET_IPHONE_SIMULATOR) {
        NSLog(@"这个是模拟器");
        return;
    }
    
    BOOL availableType = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!availableType) {
        NSLog(@"不可用");
        return;
    }
    
    //后置摄像头
    BOOL availableCameraRear = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    
    BOOL availableCameraFront = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!availableCameraRear && !availableCameraFront) {//前后摄像头都不能用  o(╯□╰)o
        [MBProgressHUD showMessage:@"摄像头暂时无法使用" toView:self.view];
        return;
    }
    
    [MBProgressHUD showLoadingMessage:nil view:self.view];
    
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    
    controller.sourceType = UIImagePickerControllerSourceTypeCamera;
    controller.cameraDevice = availableCameraRear ? UIImagePickerControllerCameraDeviceRear : UIImagePickerControllerCameraDeviceFront;
    controller.allowsEditing = YES;
    controller.delegate = delegate;
    
    [self yt_presentViewController:controller animated:YES completion:NULL];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)presentAlbumControllerWithDelegate:(id<TZImagePickerControllerDelegate>)delegate max:(NSInteger)max callback:(albumControllerCallback)callback isClip:(BOOL)isClicp {
    
    [self presentAlbumControllerWithDelegate:delegate max:max callback:callback clipSize:isClicp ? CGSizeMake(300.f, 300.f * 1.4f) : CGSizeMake(kScreenWidth, kScreenHeight)];
    
}

- (void)presentAlbumControllerWithDelegate:(id<TZImagePickerControllerDelegate>)delegate max:(NSInteger)max callback:(albumControllerCallback)callback clipSize:(CGSize)clipSize {
    
    [MBProgressHUD showLoadingMessage:nil view:self.view];
    
    if (!self.pickerController) {
        self.pickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:max delegate:delegate];
    }
//    self.pickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:max delegate:delegate];
    self.pickerController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
    self.pickerController.barItemTextColor = [UIColor blackColor];
    self.pickerController.barItemTextFont = [UIFont systemFontOfSize:14];
    self.pickerController.statusBarStyle = UIStatusBarStyleDefault;
    self.pickerController.allowCrop = clipSize.width == 0 ? NO : YES;
    self.pickerController.allowPickingVideo = NO;
    self.pickerController.sortAscendingByModificationDate = NO;
    self.pickerController.naviBgColor = [UIColor whiteColor];
    self.pickerController.cropRect = CGRectMake((self.view.width-clipSize.width)/2.f, self.view.height/2.f-clipSize.height/2.f, clipSize.width, clipSize.height);
    self.pickerController.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (callback) {
            callback(photos);
        }
    };
    
    [self yt_presentViewController:self.pickerController animated:YES completion:NULL];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)presentAlbumAndVideoControllerWithDelegate:(id<TZImagePickerControllerDelegate>)delegate max:(NSInteger)max callback:(AlbumControllerAssetsCallback)callback {
    
    [MBProgressHUD showLoadingMessage:nil view:self.view];
    
    if (!self.pickerController) {
        self.pickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:max delegate:delegate];
    }

//    self.pickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:max delegate:delegate];
    self.pickerController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
    self.pickerController.barItemTextColor = [UIColor blackColor];
    self.pickerController.barItemTextFont = [UIFont systemFontOfSize:14];
    self.pickerController.statusBarStyle = UIStatusBarStyleDefault;
    self.pickerController.allowPickingVideo = NO;
    self.pickerController.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (callback) {
            callback(photos, assets);
        }
    };
    
    [self yt_presentViewController:self.pickerController animated:YES completion:NULL];
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
}

- (void)isNeedRotation:(BOOL)needRotation {
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    __weak __typeof(self) weakSelf = self;
    IMP originalIMP = method_getImplementation(class_getInstanceMethod([appDelegate class], @selector(application:supportedInterfaceOrientationsForWindow:)));
    
    IMP newIMP = imp_implementationWithBlock(^(id obj, UIApplication *application, UIWindow *window){
        if (!weakSelf) {
            class_replaceMethod([appDelegate class], @selector(application:supportedInterfaceOrientationsForWindow:), originalIMP, method_getTypeEncoding(class_getInstanceMethod([appDelegate class], @selector(application:supportedInterfaceOrientationsForWindow:))));
        }
        return needRotation ? UIInterfaceOrientationMaskAll : UIInterfaceOrientationMaskPortrait;
    });
    
    class_replaceMethod([appDelegate class], @selector(application:supportedInterfaceOrientationsForWindow:), newIMP, method_getTypeEncoding(class_getInstanceMethod([appDelegate class], @selector(application:supportedInterfaceOrientationsForWindow:))));
}



@end
